#include<iostream>
#include<unistd.h>
#include<sys/types.h>
#include<sys/wait.h>
#include<stdio.h>
#include<string.h>

void ChildWrite(int wfd)
{
    char buffer[1024];
    int cnt = 0;
    while(true)
    {
        snprintf(buffer, sizeof(buffer), "I am child , pid: %d, cnt: %d", getpid(), cnt++);
        write(wfd, buffer, strlen(buffer));
        //break;
        sleep(1);
    }
}

void FatherRead(int rfd)
{
    char buffer[1024];
    while(true)
    {
        ssize_t n = read(rfd, buffer, sizeof(buffer) - 1);
        if(n > 0)
        {
            //sleep(3);
            buffer[n] = 0;//这也是为什么要sizeof(buffer)-1,就是预留一个给'\0'
            std::cout << "Child say: " << buffer << std::endl;
        }
        else if(n == 0)
        {
            std::cout << "n : " << n << std::endl;
            std::cout << "子进程退出不写了，我父进程也不读了" << std::endl;
            break;
        }
        else
        {
            break;
        }
        break;
    }
}

int main()
{
    int fds[2] = {0};
    int n = pipe(fds);
    if(n < 0)
    {
        std::cerr << "pipe failed !" << std::endl;
        return 1;
    }
    // //检测是否创建正确
    // std::cout <<"fds[0]: "<< fds[0] << std::endl;
    // std::cout <<"fds[1]: "<< fds[1] << std::endl;

    pid_t id = fork();
    if(id < 0)
    {
        std::cerr << "fork failed!" << std::endl;
        return 1;
    }
    if(id == 0)//子进程
    {
        //先关掉子进程管道文件的读端
        close(fds[0]);

        //封装的写函数
        ChildWrite(fds[1]);

        //最后关掉写端
        close(fds[1]);
        exit(0);
        
    }
    //这里是父进程
    close(fds[1]);

    FatherRead(fds[0]);

    close(fds[0]);
    //父进程接收子进程退出信息
    int status = 0;
    int ret = waitpid(id, &status, 0);//获取子进程的退出信息码
    if(ret > 0)
    {
        printf("exit code : %d , exit signal : %d\n", (status>>8)&0xFF, status&0x7F);
        sleep(5);
    }

    return 0;
}